package rmi;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * @author REMY Timothée and CARTIER Arthur
 * 
 */
public class Connection extends UnicastRemoteObject implements Remote,
		ConnectionInterface {

	private static final long serialVersionUID = -5281563032578493232L;

	/**
	 * @uml.property name="rmiR"
	 */
	private Registry rmiR;

	private Me me = null;

	/**
	 * @uml.property name="port"
	 */
	private int port;

	/**
	 * @uml.property name="addr"
	 */
	private String addr;

	public Connection(final int port, final Registry rmiR, final Me me)
			throws RemoteException {
		super(port);
		this.rmiR = rmiR;
		this.me = me;
	}

	/**
	 * @see rmi.ConnectionInterface#connect(rmi.User, rmi.ConnectionInterface)
	 * @param newConnectedFriend
	 * @param friendsConnectionObject
	 * @return
	 */
	@Override
	public UserInterface connect(final UserInterface newConnectedFriend,
			final ConnectionInterface friendsConnectionObject)
			throws RemoteException {
		if (!me.getBlacklist().contains(newConnectedFriend.getPseudo())) {
			final String newFriendPseudo = newConnectedFriend.getPseudo();
			if (!me.getBlacklist().contains(newFriendPseudo)) {
				if (me.getFriends().containsKey(newFriendPseudo)) {
					me.getFriends().get(newFriendPseudo)
							._setDistantUser(newConnectedFriend);
				} else {
					me.getFriends().put(newFriendPseudo,
							new UserBuffer(newConnectedFriend, me));
				}
			}
			return me;
		} else {
			return null;
		}

	}

	/**
	 * Getter of the property <tt>addr</tt>
	 * 
	 * @return Returns the addr.
	 * @uml.property name="addr"
	 */
	public String getAddr() {
		return addr;
	}

	/**
	 * Getter of the property <tt>port</tt>
	 * 
	 * @return Returns the port.
	 * @uml.property name="port"
	 */
	public int getPort() {
		return port;
	}

	/**
	 * @return
	 * @uml.property name="rmiR"
	 */
	public Registry getRmiR() {
		return rmiR;
	}

	/**
	 * Setter of the property <tt>addr</tt>
	 * 
	 * @param addr
	 *            The addr to set.
	 * @uml.property name="addr"
	 */
	public void setAddr(final String addr) {
		this.addr = addr;
	}

	/**
	 * Setter of the property <tt>port</tt>
	 * 
	 * @param port
	 *            The port to set.
	 * @uml.property name="port"
	 */
	public void setPort(final int port) {
		this.port = port;
	}

	/**
	 * @param rmiR
	 * @uml.property name="rmiR"
	 */
	public void setRmiR(final Registry rmiR) {
		this.rmiR = rmiR;
	}

}
